package com.jsmile.cloud.goodscenter.web.mq.order;

import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.jsmile.cloud.goodscenter.spu.model.RepertoryRecord;
import com.jsmile.cloud.goodscenter.spu.service.RepertoryRecordApplicationService;
import com.jsmile.cloud.tradecenter.api.enums.OrderStatusEnum;
import com.jsmile.cloud.tradecenter.api.to.OrderStatusChangeTo;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单关闭策略
 */
@Slf4j
@Component
public class OrderCloseStrategy implements IOrderStatusStrategy {

    @Resource
    private RepertoryRecordApplicationService repertoryRecordApplicationService;

    @Override
    public OrderStatusEnum orderStatus() {
        return OrderStatusEnum.CLOSE;
    }

    @Override
    public void execute(OrderStatusChangeTo orderStatusChangeTo) {
        log.info("订单关闭事件：{}", JSONUtil.toJsonStr(orderStatusChangeTo));
        addStock(orderStatusChangeTo);
    }

    /**
     * 回滚添加库存
     *
     * @param orderStatusChangeTo
     */
    private void addStock(OrderStatusChangeTo orderStatusChangeTo) {
        repertoryRecordApplicationService.create(orderStatusChangeTo.getOrder().getOrderProducts().stream().map(x -> {
            return RepertoryRecord.builder().tenantId(orderStatusChangeTo.getOrder().getTenantId()).orderNo(orderStatusChangeTo.getOrder().getOrderNo() + "")
                .shopId(orderStatusChangeTo.getOrder().getShopId()).skuId(x.getSkuId()).activityId(orderStatusChangeTo.getOrder().getActivityId()).spuId(x.getSpuId())
                .num(x.getProductNumber()).status(1).build();
        }).collect(Collectors.toList()));
    }
}
